<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

    <link rel="icon" href="../../images/webpage/thumb_equipment_randomreward_01.png">

    <title>priconne-quest-helper Data Export</title>
    <meta name="title" content="priconne-quest-helper Data Export"/>

    <!-- META DATA -->
    <meta name="description" content="priconne-quest-helper Data Export">
    <meta name="author" content="S'pugn">

    <!-- OPEN GRAPH / FACEBOOK META DATA -->
    <meta property="og:title" content="priconne-quest-helper Data Export"/>
    <meta property="og:description" content="priconne-quest-helper Data Exporting - Transfer Data Between Devices!"/>
    <meta property="og:type" content="website"/>
    <meta property="og:image" content="https://raw.githubusercontent.com/Expugn/priconne-quest-helper/master/images/webpage/thumb_equipment_randomreward_01.png"/>
    <meta property="og:image:width" content="50"/>
    <meta property="og:image:height" content="50"/>
    <meta property="og:url" content="https://expugn.github.io/priconne-quest-helper/"/>
    <meta property="og:locale" content="en_US"/>

    <!-- TWITTER META DATA -->
    <meta name="twitter:card" content="summary"/>
    <meta name="twitter:site" content="@eSpugn"/>
    <meta name="twitter:creator" content="@eSpugn"/>
    <meta name="twitter:title" content="priconne-quest-helper Data Export"/>
    <meta name="twitter:description" content="priconne-quest-helper Data Exporting - Transfer Data Between Devices!"/>

    <!-- SCRIPTS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="../../vendor/modernizr/modernizr-custom.js"></script> <!-- WEBP CHECK -->

    <!-- CSS STYLE SHEETS -->
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="../../css/data.css">
</head>

<body>
<noscript>
    <style type="text/css">
        div {display: none;}
        hr {display: none;}
        footer {display: none;}
    </style>
    <h1 style="color: white; font-family: 'Trebuchet MS', Arial, serif; text-align:center; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); text-shadow: 1px 1px 2px #000000;">
        <span style="color: orangered;">JavaScript is disabled!</span>
        <br><br>
        <span style="color: deepskyblue;">priconne-quest-helper/export-data/</span> cannot function without JavaScript.
        <br><br>
        <span style="color: #ffdf73;">Please enable JavaScript to continue!</span>
    </h1>
</noscript>

<div>
    <h1 class="title main_title">Princess Connect! Re:Dive - Quest Helper</h1>
    <h2 class="title sub_title">Data Export</h2>
    <h1 class="title simple_title">priconne-quest-helper &boxv; Data Export</h1>
</div>
<hr>

<div id="gist-create-iframe" style="display: none">
    <!-- REPLACE URL WITH LATEST HEROKU URL -->
    <iframe id="gist-creator" name="gist-creator" src="https://thawing-fortress-48694.herokuapp.com/"></iframe>
</div>


<div id="localstorage-failure" style="display: none">
    <h2 class='align-center'>
        LocalStorage is Not Supported On This Browser!<br>
        Data Exporting Will Not Function Properly.
    </h2>
</div>

<div id="export-failure" style="display: none">
    <h2 class='align-center'></h2>
</div>

<div id="all-export-elements" style="display: none">
    <div id="export-settings" style="overflow-x: auto;">
        <h2 class='align-center'>Export Options</h2>
        <div class="center-div">
            <div style="display: inline-block; padding: 0 15px;">
                <label style="display: block;" for="include-projects">Projects</label>
                <input id="include-projects" type="checkbox" checked onchange="checked_checkbox()">
            </div>
            <div style="display: inline-block; padding: 0 15px;">
                <label style="display: block;" for="include-blacklist">Blacklist</label>
                <input id="include-blacklist" type="checkbox" checked onchange="checked_checkbox()">
            </div>
            <div style="display: inline-block; padding: 0 15px;">
                <label style="display: block;" for="include-inventory">Inventory</label>
                <input id="include-inventory" type="checkbox" checked onchange="checked_checkbox()">
            </div>
            <div style="display: inline-block; padding: 0 15px;">
                <label style="display: block;" for="include-settings">Settings</label>
                <input id="include-settings" type="checkbox" onchange="checked_checkbox()">
            </div>
        </div>
        <div class="center-div">
            <button id="generate-url-button" type="button" class="align-center" onclick="generate_url()">Generate URL</button>
        </div>
        <br>
    </div>

    <div id="generated-links" style="display: none">
        <div id="url"></div>
        <button type="button" onclick="copyURLToClipboard()">Copy URL to Clipboard</button>
        <span>URLs older than a month will occasionally be purged.</span>
    </div>

    <hr>

    <div id="data-display"></div>
</div>
</body>

<script>
    let project_data, priority_project_data, blacklist_data, inventory_data, settings_data;
    let project_json, priority_project_json, blacklist_json, inventory_json, settings_json;
    let url, receiverWindow;
    const hash = ["b52d", "343b", "0780", "1f11", "2451", "2ea6", "b3a5", "1315", "58ad", "6ff8", "8704351629"];
    let hash_string = "";

    const heroku_url = "https://thawing-fortress-48694.herokuapp.com";
    window.onload = function()
    {
        receiverWindow = document.getElementById("gist-creator").contentWindow;
    };

    window.addEventListener('message', function (e) {
        if (~e.origin.indexOf(heroku_url)) {
            hash_string = "";
            console.log(e.data + " from " + heroku_url);

            url += e.data;

            document.getElementById("url").innerHTML = url;
            document.getElementById("generated-links").style.display = "block";
            document.getElementById("export-settings").style.display = "none";

            // URL CREATION COMPLETED
        }
        else {
            console.log("[Export Data] - Received message... but it's from the wrong url: " + e.origin);
        }
    });

    function send_data_to_heroku(content) {
        try {
            receiverWindow.postMessage(location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: ''), heroku_url);
            receiverWindow.postMessage(content, heroku_url);
            receiverWindow.postMessage(hash_string, heroku_url);
            receiverWindow.postMessage("priconne_gist", heroku_url);
        }
        catch (err) {
            document.getElementById("export-failure").innerHTML = "<h2 class='align-center'>Failed to Send Data!<br>Refresh the page and try again.</h2>";
            document.getElementById("all-export-elements").style.display = "none";
            document.getElementById("export-failure").style.display = "block";
        }
    }

    setTimeout(function () {
        if (typeof(Storage) !== "undefined") {
            build_data_tables();
            checked_checkbox();
        }
        else {
            document.getElementById("localstorage-failure").style.display = "block";
        }
    }, 1000);



    function build_data_tables() {
        try {
            project_data = localStorage.getItem('projects');
            priority_project_data = localStorage.getItem('priority_projects');
            blacklist_data = localStorage.getItem('blacklist');
            inventory_data = localStorage.getItem('inventory');
            settings_data = localStorage.getItem('settings');

            project_json = (project_data !== null ? JSON.parse(project_data) : "");
            priority_project_json = (priority_project_data !== null ? JSON.parse(priority_project_data) : "");
            blacklist_json = (blacklist_data !== null ? JSON.parse(blacklist_data) : "");
            inventory_json = (inventory_data !== null ? JSON.parse(inventory_data) : "");
            settings_json = (settings_data !== null ? JSON.parse(settings_data) : "");

            data_success();
        }
        catch (err) {
            document.getElementById("export-failure").innerHTML = "<h2 class='align-center'>Invalid Data Received!</h2>";
            document.getElementById("export-failure").style.display = "block";
        }
    }

    function data_success() {
        try {
            display_data();

            if (project_data === null) {
                document.getElementById("include-projects").checked = false;
                document.getElementById("include-projects").disabled = true;
            }
            if (blacklist_data === null) {
                document.getElementById("include-blacklist").checked = false;
                document.getElementById("include-blacklist").disabled = true;
            }
            if (inventory_data === null) {
                document.getElementById("include-inventory").checked = false;
                document.getElementById("include-inventory").disabled = true;
            }
            if (settings_data === null) {
                document.getElementById("include-settings").checked = false;
                document.getElementById("include-settings").disabled = true;
            }

            document.getElementById("all-export-elements").style.display = "block";
        }
        catch (error_message) {
            document.getElementById("export-failure").innerHTML = "<h2 class='align-center'>" + error_message + "</h2>";
            document.getElementById("export-failure").style.display = "block";
        }
    }


    function generate_url() {
        // DISABLE GENERATE URL BUTTON SO USER DOESN'T SPAM IT
        document.getElementById("generate-url-button").disabled = true;
        document.getElementById("include-projects").disabled = true;
        document.getElementById("include-blacklist").disabled = true;
        document.getElementById("include-inventory").disabled = true;
        document.getElementById("include-settings").disabled = true;

        for (const i in hash[hash.length - 1]) {
            hash_string += hash[parseInt(hash[hash.length - 1][i])];
        }
        // TEST IF RATE LIMITED HERE
        check_rate_limit_status(hash_string, function (is_rate_limited, date_string) {
            if (!is_rate_limited)
            {
                // DO STUFF
                let include_projects = document.getElementById("include-projects").checked;
                let include_blacklist = document.getElementById("include-blacklist").checked;
                let include_inventory = document.getElementById("include-inventory").checked;
                let include_settings = document.getElementById("include-settings").checked;

                url = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname.substring(0, window.location.pathname.indexOf('/')) + window.location.pathname.split('/')[1] + "/pages/import-data/?id=";

                let content;
                let content_map = new Map();
                if (include_projects)
                {
                    content_map["projects"] = localStorage.getItem('projects');
                    if (priority_project_data !== null)
                    {
                        content_map["priority_projects"] = localStorage.getItem('priority_projects');
                    }
                }
                else if (project_data !== null) { document.getElementById("project-display").style.display = "none"; }
                if (include_blacklist) { content_map["blacklist"] = localStorage.getItem('blacklist'); }
                else if (blacklist_data !== null) { document.getElementById("blacklist-display").style.display = "none"; }
                if (include_inventory) {content_map["inventory"] = localStorage.getItem('inventory');}
                else if (inventory_data !== null) { document.getElementById("inventory-display").style.display = "none"; }
                if (include_settings) { content_map["settings"] = localStorage.getItem('settings'); }
                else if (settings_data !== null) { document.getElementById("settings-display").style.display = "none"; }

                content = JSON.stringify(content_map);

                console.log("[Data Export] - Content Generated: " + content);

                send_data_to_heroku(content);
            }
            else {
                // ABANDON SHIP, RATE LIMITED.
                document.getElementById("export-failure").innerHTML = "<h2 class='align-center'>Rate Limited!<br>Rate Limit Reset: " + date_string + "</h2>";
                document.getElementById("export-failure").style.display = "block";
            }
        });
    }

    function copyURLToClipboard() {
        let dummy = document.createElement("input");
        document.body.appendChild(dummy);
        dummy.setAttribute('value', document.getElementById("url").innerHTML);
        dummy.select();
        document.execCommand("copy");
        document.body.removeChild(dummy);
    }

    function checked_checkbox() {
        document.getElementById("generate-url-button").disabled = !(document.getElementById("include-projects").checked || document.getElementById("include-blacklist").checked || document.getElementById("include-inventory").checked || document.getElementById("include-settings").checked);
    }

    function display_data() {
        const display = document.getElementById("data-display");
        const projects_provided = project_json !== "",
              blacklist_provided = blacklist_json !== "",
              inventory_provided = inventory_json !== "",
              settings_provided = settings_json !== "";
        if (!projects_provided && !blacklist_provided && !inventory_provided && !settings_provided) {
            throw "No Data Available to Export!";
        }
        else {
            if (projects_provided)
                build_project_display();
            if (blacklist_provided)
                build_blacklist_display();
            if (inventory_provided)
                build_inventory_display();
            if (settings_provided)
                build_settings_display();
        }

        function get_item_sprite_class(item_name) {
            return "is__" + item_name.replace("'", "").replace(/\W/g, '-').toLowerCase().replace('---', '-');
        }

        function build_project_display() {
            // CONVERT PROJECT JSON
            let project_data = {};
            for (const index in project_json) {
                const info = project_json[index];
                project_data[info[0]] = JSON.parse(info[1]);
            }

            // BUILD DISPLAY
            const project_display = document.createElement("div");
            project_display.id = "project-display";
            const title = document.createElement("h1");
            title.innerText = "\u2E3A Projects \u2E3A";
            project_display.appendChild(title);
            const count = document.createElement("h4");
            count.classList.add("item-count");
            count.innerText = Object.keys(project_data).length + " project(s) found.";
            project_display.appendChild(count);
            for (const project_name in project_data) {
                const project_info = project_data[project_name];
                const project_title = document.createElement("h3");
                project_title.classList.add("project-title");
                project_title.innerText = project_name;
                const project_items = document.createElement("div");
                project_info.forEach(function (e) {
                    const item_name = e[0], item_amount = e[1];
                    const img = document.createElement("span"),
                          amount = document.createElement("span");
                    img.classList.add("item-sprite", get_item_sprite_class(item_name));
                    amount.classList.add("amount");
                    amount.innerText = item_amount;
                    img.appendChild(amount);
                    project_items.appendChild(img);
                });
                project_display.appendChild(project_title);
                project_display.appendChild(project_items);
            }
            display.appendChild(project_display);
        }

        function build_blacklist_display() {
            const blacklist_display = document.createElement("div");
            blacklist_display.id = "blacklist-display";
            const title = document.createElement("h1");
            title.innerText = "\u2E3A Blacklist \u2E3A";
            blacklist_display.appendChild(title);
            const count = document.createElement("h4");
            count.classList.add("item-count");
            count.innerText = blacklist_json.length + " blacklisted item(s) found.";
            blacklist_display.appendChild(count);
            const blacklist_items = document.createElement("div");
            for (let i = 0, j = blacklist_json.length ; i < j ; i++) {
                const item_name = blacklist_json[i];
                const img = document.createElement("i");
                img.classList.add("item-sprite", get_item_sprite_class(item_name));
                img.tile = item_name;
                blacklist_items.appendChild(img);
            }
            blacklist_display.appendChild(blacklist_items);
            display.appendChild(blacklist_display);
        }

        function build_inventory_display() {
            const inventory_display = document.createElement("div");
            inventory_display.id = "inventory-display";
            const title = document.createElement("h1");
            title.innerText = "\u2E3A Inventory \u2E3A";
            inventory_display.appendChild(title);
            const inventory_items = document.createElement("div");
            Object.keys(inventory_json.fragments).forEach(function (frag_name) {
                const img = document.createElement("span"),
                      amount = document.createElement("span");
                img.classList.add("item-sprite", get_item_sprite_class(frag_name));
                amount.classList.add("amount");
                amount.innerText = inventory_json.fragments[frag_name];
                img.appendChild(amount);
                inventory_items.appendChild(img);
            });
            inventory_display.appendChild(inventory_items);
            display.appendChild(inventory_display);
        }

        function build_settings_display() {
            const settings_display = document.createElement("div");
            settings_display.id = "settings-display";
            const title = document.createElement("h1");
            title.innerText = "\u2E3A Settings \u2E3A";
            settings_display.appendChild(title);
            const textarea = document.createElement("textarea");
            textarea.rows = 10;
            textarea.cols = 60;
            textarea.disabled = true;
            textarea.innerHTML = JSON.stringify(settings_json, null, 4);
            settings_display.appendChild(textarea);
            display.appendChild(settings_display);
        }
    }

    function check_rate_limit_status(hash_s, callback) {
        const rate_limit_cooldown = 5;
        // CHECK RATE LIMIT STATUS
        $.ajax({
            url: 'https://api.github.com/rate_limit',
            type: 'GET',
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Authorization", "token " + hash_s);
            },
            success: function(response) {
                if (callback) {
                    let rate_limit_remaining = JSON.parse(response["resources"]["core"]["remaining"]);
                    let rate_limit_reset = parseInt(response["resources"]["core"]["reset"]);
                    let rate_limit_limit = parseInt(response["resources"]["core"]["limit"]);

                    console.log(rate_limit_remaining + " / " + rate_limit_limit + " API calls remaining.");
                    if (rate_limit_remaining < rate_limit_cooldown) {
                        let time = new Date() + rate_limit_reset;
                        let date = new Date(time);
                        console.log("Under cooldown! " + date.toString() + " for the next reset.");
                        callback(true, date.toString());
                    }
                    else {
                        callback(false, "");
                    }
                }
            },
            error: function(e) {
                console.log("Rate limit status check error: " + e);
            }
        });
    }
</script>
</html>